package com.swufe.lianxi;

import androidx.appcompat.app.AppCompatActivity;
import androidx.arch.core.internal.SafeIterableMap;
import androidx.collection.ArraySet;
import androidx.collection.LongSparseArray;
import androidx.collection.SimpleArrayMap;

import android.app.ListActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.MalformedInputException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class RatelistActivity extends ListActivity implements Runnable {
    private static final String TAG = "Ratelist";
    String list_data[] = {"one", "two", "three", "four"};
    Handler handler;
    private String logDate="";
    private final String DATE_SP_KEY="lastRateDateStr";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_ratelist);
        SharedPreferences sp=getSharedPreferences("myrate", Context.MODE_PRIVATE);
        logDate=sp.getString(DATE_SP_KEY,"");
        Log.i("List", "lastRateDataStr="+logDate);

        List<String> list1 = new ArrayList<>();
        for (int i = 1; i < 100; i++) {
            list1.add("item" + i);
        }
        //构造适配器
        ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list1);
        setListAdapter(adapter);
        String[] list_data = {"one", "two", "three", "four"};
        //开启子线程运行
        Thread t = new Thread(this);
        t.start();
        handler = new Handler(Looper.myLooper()) {//handler 传递消息
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 5) {
                    List<String> list2 = (List<String>) msg.obj;
                    ListAdapter adapter = new ArrayAdapter<String>(RatelistActivity.this,
                            android.R.layout.simple_list_item_1, list2);
                    setListAdapter(adapter);
                    Log.i(TAG, "handleMessage: list2...");
                    //ListAdapter adapter = new ArrayAdapter<String>(RatelistActivity.this, android.R.layout.simple_list_item_1, list2);
                    //setListAdapter(adapter);
                    Toast.makeText(RatelistActivity.this, "汇率已更新", Toast.LENGTH_SHORT).show();
                }
                super.handleMessage(msg);
            }
        };
    }

    @Override
    public void run() {
        Log.i("List", "run:run()....");
        List<String>retList=new ArrayList<String>();
        Message msg=handler.obtainMessage();
        String curDateStr=(new SimpleDateFormat("yyyy-mm-dd")).format(new Date());
        Log.i("run", "curDateStr: "+curDateStr+"logData:"+logDate);
        if(curDateStr.equals(logDate)) {
            //如果相等，则不从网络中获取数据
            Log.i("run", "日期相等，从数据库中获取数据 ");
            DBManeger dbManeger = new DBManeger(RatelistActivity.this);
            for (RateItem rateItem : dbManeger.listAll()) {
                retList.add(rateItem.getCurName() + "=>" + rateItem.getCurRate());
            }
        }else{
                Log.i("run", " 日期相等，从网络中获取在线数据");
       /** Log.i(TAG, "run: ...");
        List<String> relist = new ArrayList<>();
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //Bundle bundle = new Bundle();
        //Document doc = null;**/
        try {
            List<RateItem>relist=new ArrayList<RateItem>();
            /**URL url=new URL("http://www.usd-cny.com/bankofchina.htm");
            HttpURLConnection httpURLConn= (HttpURLConnection) url.openConnection();
            InputStream in=httpURLConn.getErrorStream();
            String retStr = IOUtils.toString(in, "gb2312");
            Document doc = Jsoup.parse(retStr);
            Elements tables = doc.getElementsByTag("table");
            Element retable = tables.get(5);
            Elements tds = retable.getElementsByTag("td");**/
            String url = "https://www.boc.cn/sourcedb/whpj/ ";
            Document doc = Jsoup.connect(url).get();
            Log.i(TAG, "run: " + doc.title());
            Elements tables = doc.getElementsByTag("table");
            Element table1 = tables.get(1);
            Log.i(TAG, "run: table1=" + table1);
            Elements tds = table1.getElementsByTag("td");
            int tdsize=tds.size();
            for (int i = 0; i < tdsize; i += 8) {
                Element td1 = tds.get(i);
                Element td2 = tds.get(i + 5);
                float val = Float.parseFloat(td2.text());
                val = 100 / val;
                retList.add(td1.text() + "==>" + val);
                RateItem rateItem=new RateItem(td1.text(),td2.text());
                ArraySet<RateItem> rateList = new ArraySet<RateItem>();
                rateList.add(rateItem);
            }
            DBManeger dbManager = new DBManeger(RatelistActivity.this);
            dbManager.deleAll();
            Log.i("db","删除所有记录");
            dbManager.addAll(relist);
            Log.i("db","添加新记录集");

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

            //更新记录日期
            SharedPreferences sp = getSharedPreferences("myrate", Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sp.edit();
            edit.putString(DATE_SP_KEY, curDateStr);
            edit.commit();
            Log.i("run","更新日期结束：" + curDateStr);
        }

        msg.obj = retList;
        int msgWhat = 5;
        msg.what = msgWhat;
        handler.sendMessage(msg);
    }
}
            /**String url = "https://www.boc.cn/sourcedb/whpj/ ";
            Document doc = Jsoup.connect(url).get();
            Log.i(TAG, "run: " + doc.title());
            Elements tables = doc.getElementsByTag("table");
            Element table1 = tables.get(1);
            Log.i(TAG, "run: table1=" + table1);
            //Element table6 = tables.get(5);
            //Log.i(TAG, "run: table6=" + table6);
            //获取TD中的数据
            //Elements tds = table6.getElementsByTag("td");
            Elements tds = table1.getElementsByTag("td");
            for (int i = 0; i < tds.size(); i += 8) {
                Element td1 = tds.get(i);
                Element td2 = tds.get(i + 5);
                String str1 = td1.text();
                String val = td2.text();
                Log.i(TAG, "run: " + str1 + "==>" + val);
                relist.add(str1 + "==>" + val);//敲重点，下次不能忘了
            }
            Message msg = handler.obtainMessage(5);
            msg.obj = relist;
            handler.sendMessage(msg);
            // msg.obj = rateList;
            // handler.sendMessage(msg);
            Log.i("thread","sendMessage....");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }**/
